package com.baoxin.chenxixc4coach.fragments.student.subject;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.baoxin.chenxixc4coach.MyCallback;
import com.baoxin.chenxixc4coach.R;
import com.baoxin.chenxixc4coach.adapter.TestStudentAdapter;
import com.baoxin.chenxixc4coach.bean.TestStudent;
import com.baoxin.chenxixc4coach.fragments.TitleFragment;
import com.baoxin.chenxixc4coach.java.MyHandler;
import com.baoxin.chenxixc4coach.java.SimpleResultHelper;
import com.baoxin.chenxixc4coach.utils.Interfaces;
import com.baoxin.chenxixc4coach.utils.Msg;
import com.baoxin.chenxixc4coach.utils.MyLog;
import com.baoxin.chenxixc4coach.utils.NetUtil;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class TestStutentFragment extends TitleFragment implements TestStudentAdapter.TestStuClickListener {
    private int subject_type;// 1 2 3 4对应科目1234
    private RecyclerView recyclerView;
    private List<TestStudent> studentList;
    private TestStudentAdapter adapter;
    private Handler handler;

    public void setSubject_type(int subject_type) {
        this.subject_type = subject_type;
    }

    @Override
    public String getTabTitle() {
        return "考试学员";
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isVisibleToUser && handler != null) {
            loadData();
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_single_list, container, false);
        recyclerView = view.findViewById(R.id.student_recycler_view);
        studentList = new ArrayList<>();

        adapter = new TestStudentAdapter(getContext(), this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        recyclerView.setAdapter(adapter);

        handler = new MyHandler(this, activity) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case Msg.REQUEST_SUCCEED:
                        studentList = (List<TestStudent>) msg.obj;
                        adapter.setData(studentList);
                        adapter.notifyDataSetChanged();
                        break;
                }
            }
        };
        request();

        return view;
    }

    //根据subject_type来获取数据
    private void request() {

        JSONObject body = new JSONObject();
        try {
            //  body.put("serRes", 1);不给查询所有
            body.put("serSubject", subject_type);

            NetUtil.post(activity, Interfaces.URL_TEST_STUDENT, body.toString(), new MyCallback(Interfaces.URL_TEST_STUDENT, handler));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void showSetGradeDialog(final TestStudent student) {

        AlertDialog dialog = new AlertDialog.Builder(activity).setTitle("设置考试成绩")
                .setItems(resString, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        setGrade(student, which);
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();
    }


    final String[] resString = new String[]{"不合格", "缺考", "及格"};

    private void setGrade(final TestStudent student, final int which) {
        JSONObject body = new JSONObject();

        try {
            body.put("serId", student.getSerId());
            Integer serRes = null;
            if (which == 0) {
                serRes = -1;
            } else if (which == 1) {
                serRes = 0;
            } else if (which == 2) {
                serRes = 1;
            }
            body.put("serRes", serRes);
            //     body.put("serReason", "");

            NetUtil.post(activity, Interfaces.URL_EXAM_ADD, body.toString(), new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (!activityAlive()) return;
                    String result = response.body().string();
                    if (SimpleResultHelper.isSucceed(result)) {

                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(activity, "设置成绩成功！", Toast.LENGTH_SHORT).show();
                                student.setSerRes(which - 1);
                                adapter.notifyDataSetChanged();
                            }
                        });

                    } else if (!SimpleResultHelper.isSucceed(result)) {
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(activity, "设置成绩失败！", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void loadData() {
        request();
    }
}
